import requests
import bs4
import json
#可以用api的方法直接获取图片
class separate_video():
    def __init__(self):
        self.bv = input('请输入视频的BV号：\n')
        self.url = 'https://www.bilibili.com/video/' + self.bv
    def get_url(self):
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
        }
        res = requests.get(self.url,headers=headers)
        return res


    def get_image(self):
        res = self.get_url()
        soup = bs4.BeautifulSoup(res.text,'html.parser')
        image_url = soup.find(itemprop="image")
        return image_url['content']

    def save_image(self):
        image_url = self.get_image()
        r = requests.get(image_url)
        with open('D:\pythonProject\图片\{}封面.jpg'.format(self.bv),'wb')as f:
            f.write(r.content)
            f.close()

class up_videos():
    def __init__(self):
        self.uid = input('请输入up的uid：\n')
        self.pn = int(input('请输入获取的视频页数：（一页30个视频）\n'))

    def get_images(self):
        for i in range(1,self.pn+1):
            url = 'https://api.bilibili.com/x/space/arc/search?mid={}&ps=30&tid=0&pn={}&keyword=&order=pubdate&jsonp=jsonp'.format(self.uid,i)
            res = requests.get(url)
            res_json = json.loads(res.text)
            self.save_image(res_json)
    def save_image(self,res_json):

        long = len(res_json['data']['list']['vlist'])
        for i in range(long):
            image_url = res_json['data']['list']['vlist'][i]['pic']
            print(image_url)
            image = requests.get(image_url)
            with open('D:\pythonProject\图片\{}封面.jpg'.format(res_json['data']['list']['vlist'][i]['bvid']),'wb')as f:
                f.write(image.content)
                f.close()
class bv_to_av():
    def __init__(self):
        self.bv = input('请输入视频BV号：\n')
        self.table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
        self.tr = {}
        for i in range(58):
            self.tr[self.table[i]] = i
        self.s = [11, 10, 3, 8, 4, 6]
        self.xor = 177451812
        self.add = 8728348608

    def dec(self):
        r = 0
        for i in range(6):
            r += self.tr[self.bv[self.s[i]]] * 58 ** i
        return (r - self.add) ^ self.xor
    #av转bv
    '''def enc(self):
        self.bv = (self.bv ^ self.xor) + self.add
        r = list('BV1  4 1 7  ')
        for i in range(6):
            r[self.s[i]] = self.table[self.bv // 58 ** i % 58]
        return ''.join(r)'''
#鸡肋功能
class videoshot():
    def __init__(self,av):
        self.av = av
        self.url = 'https://api.bilibili.com/x/player/videoshot?aid={}&index=1'.format(av)

    def get_url(self):
        res = requests.get(self.url)
        res_json = json.loads(res.text)
        return 'http:'+res_json['data']['image'][0]

    def save_image(self):
        url = self.get_url()
        image = requests.get(url)
        with open('D:\pythonProject\图片\{}.jpg'.format(self.av),"wb")as f:
            f.write(image.content)
            f.close()


if __name__ == '__main__':
    while(True):
        print('1、获取单独视频封面')
        print('2、获取视频预览缩略图')
        print('3、批量获取up视频封面')
        print('4、退出程序')
        select = int(input('请选择：\n'))
        if select == 1:
            try:
                run = separate_video()
                run.save_image()

            except:
                print('输入错误或程序错误')

        elif select == 3:
            try:
                run = up_videos()
                run.get_images()
            except:
                print('输入错误或程序错误')
        elif select == 2:
            try:
                av_run = bv_to_av()
                av = av_run.dec()
                run = videoshot(av)
                run.save_image()
            except:
                print('输入错误或程序错误')
        elif select == 4:
            print('已经退出程序！')
            break
        else:
            print('输入有误，请重新输入！')
        #图片保存路径需修改为本地路径
        #支持二偷，再偷必究！
        #仅学习交流之目的，请勿用于违法用途